package com.alex.wechat.mp.handler;

import java.util.Date;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.jeecgframework.web.cgform.common.CgAutoListConstant;
import org.springframework.beans.factory.annotation.Autowired;

import com.alex.wechat.core.handler.WxHandler;
import com.alex.wechat.mp.config.WxContext;
import com.alex.wechat.mp.message.receive.entity.WxReceiveText;
import com.alex.wechat.mp.message.receive.service.WxReceiveTextServiceI;

import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.message.bean.WxXmlMessage;
import me.chanjar.weixin.message.rule.WxMessageHandler;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;

/**
 * 转发客户消息给客服Handler
 * 
 * @author Debenson
 * @since 0.1
 */
@WxHandler(priority = Integer.MIN_VALUE)
public class DefaultMsgHandler implements WxMessageHandler {

  @Autowired
  private WxReceiveTextServiceI receiveTextService;
  @Autowired
  private AutoReplyTool autoRespReplyTool;

  @Override
  public String handle(WxXmlMessage wxMessage, Map<String, Object> context)
      throws WxErrorException {
    saveReceiveText(wxMessage);

    final String key = wxMessage.getContent();
    WxMpXmlOutMessage m = null;
    if (StringUtils.isNotBlank(key)) {
      m = autoRespReplyTool.autoReply(wxMessage, key);
    }

    if (m == null) {
      // 默认的回复
      m = WxMpXmlOutMessage.TRANSFER_CUSTOMER_SERVICE().fromUser(wxMessage.getToUser())
          .toUser(wxMessage.getFromUser()).build();
    }
    return m.toXml();
  }

  /**
   * 保存接收到的信息
   * 
   * @param msg
   * @return
   */
  private WxReceiveText saveReceiveText(WxMpXmlMessage msg) {
    WxReceiveText recvMsg = new WxReceiveText();
    recvMsg.setContent(msg.getContent());
    recvMsg.setCreateDate(new Date());
    recvMsg.setUpdateDate(new Date());
    recvMsg.setFromUserName(msg.getFromUser());
    recvMsg.setToUserName(msg.getToUser());
    recvMsg.setMsgId(String.valueOf(msg.getMsgId()));
    recvMsg.setMsgType(msg.getMsgType());
    recvMsg.setResponse(CgAutoListConstant.BOOL_FALSE);
    recvMsg.setAccountId(WxContext.getOriginalId());
    recvMsg.setEvent(msg.getEvent());
    recvMsg.setEventKey(msg.getEventKey());
    recvMsg.setPictureUrl(msg.getPicUrl());
    recvMsg.setMediaId(msg.getMediaId());
    recvMsg.setThumbMediaId(msg.getThumbMediaId());
    recvMsg.setFormat(msg.getFormat());
    recvMsg.setRecognition(msg.getRecognition());
    recvMsg.setLocationX(msg.getLocationX() == null ? null : msg.getLocationX().toString());
    recvMsg.setLocationY(msg.getLocationY() == null ? null : msg.getLocationY().toString());
    recvMsg.setLocationLabel(msg.getLabel());
    receiveTextService.save(recvMsg);
    return recvMsg;
  }

}
